package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhoufei
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 手机端发送短信验证码
     * @return
     * 为指定手机号发送短信验证码，同时需要将手机号对应的验证码保存到Session，方便后续登录时进行比对
     */
    @PostMapping("/sendMsg")
    public void sendMsg(@RequestBody User user, HttpSession session){
        //1.获取手机号
        String phone = user.getPhone();
        //2.生成随机的验证码
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            System.out.println("验证码为："+ code);
            //3.发送短信
//            SMSUtils.sendMessage("速运快递","SMS_159620392",phone,code);
            //4.将登录的手机号保存到session中
            //优化方法：将生成的验证码保存到Redis中
//            session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        }
    }

    /**76
     * 手机端用户登录
     * @return
     * 查看请求，请求参数为phone=value,code=value,若要用User对象作为参数进行传递，需要对User实体类进行扩展（该类中没有code属性），也可以通过Map集合，通过键值对进行传参
     */
    @PostMapping("/login")
    public R login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
        //1.从Map中获取用户页面输入的手机号
        String phone = map.get("phone").toString();
        //2.从Ma中获取用户页面输入的验证码
        String code = map.get("code").toString();
        //3.从Session中获取之前系统随机生成的验证码
          //优化：从Redis中获取验证码
//        Object userCode = session.getAttribute(phone);
//        String userCode = session.getAttribute(phone).toString();
         String userCode = (String) redisTemplate.opsForValue().get(phone);
        //4.校验验证码
        if (userCode==null || !userCode.equals(code)){
            return R.error("登录失败");
        }
        //登录成功，判断用户是否时新用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        if (user == null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //6、将用户id保存到Session中
        session.setAttribute("user",user.getId());
        //7.优化：登录成功后，删除Rdeis中的验证码
        redisTemplate.delete(phone);
        return R.success("登录成功");
    }
}
